const {invalidGoodsId, goodsIdIsNotNullError,cartFormatError,isHasStockNumberError,carts_numDetgoods_num} = require("../constants/err.type")
const {getGoodsId} = require("../server/goods.server")
const {getCardsId} = require("../server/cart.server")

const validator = (rules) =>{
  return async (ctx, next) => {
    try {
      ctx.verifyParams(rules)

    } catch (error) {
      console.error(error)
      cartFormatError.result = error
      return ctx.app.emit('error', cartFormatError, ctx)
    }
    await next()
  }
}

const goodsIdIsNotNull = async (ctx, next) => {
  try {
    console.log(ctx.request)
    const good_id = ctx.request.body.goods_id?ctx.request.body.goods_id:ctx.request.params.id;

    const res = await getGoodsId(good_id)
    if (!res) {
      return ctx.app.emit("error", invalidGoodsId, ctx)
    }
    ctx.state.goods_num = res.dataValues.goods_num
    await next()

  } catch (error) {
    console.log('获取商品信息错误', error)
    ctx.app.emit("error", goodsIdIsNotNullError, ctx)
    return
  }
}

const isHasStockNumber = async (ctx,next) => {
  try{
    // const res = await getGoodsId(good_id);
    const goods_num = ctx.state.goods_num
    const goods_id = ctx.request.body.goods_id?ctx.request.body.goods_id:ctx.request.params.id
    const res = await getCardsId(goods_id)
    if(res){
      const carts_num = res.dataValues.number
      if(carts_num>=goods_num) {
        return ctx.app.emit("error", carts_numDetgoods_num, ctx)
      }
    }
      await next()


  }catch (error) {
    console.log("获取商品库存数失败",error)
    ctx.app.emit('error',isHasStockNumberError,ctx)
  }
}



module.exports = {
  validator,
  goodsIdIsNotNull,
  isHasStockNumber
}
